<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }
        
        #app {
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background-color: #409EFF;
            color: white;
            height: 60px;
            display: flex;
            align-items: center;
            padding: 0 20px;
            justify-content: space-between;
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
            z-index: 100;
        }
        
        .logo {
            font-size: 20px;
            font-weight: bold;
        }
        
        .user-actions {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .main-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        
        .sidebar {
            width: 220px;
            background-color: #f5f7fa;
            transition: all 0.3s;
            box-shadow: 2px 0 4px rgba(0,0,0,.1);
            overflow-y: auto;
            height: calc(100vh - 60px);
        }
        
        .sidebar.collapsed {
            width: 64px;
        }
        
        .menu-container {
            padding: 10px 0;
        }
        
        .menu-item {
            padding: 12px 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            position: relative;
        }
        
        .menu-item:hover {
            background-color: #e6f7ff;
        }
        
        .menu-item.active {
            background-color: #409EFF;
            color: white;
        }
        
        .menu-item .arrow {
            margin-left: auto;
            transition: transform 0.3s;
        }
        
        .menu-item .arrow.rotated {
            transform: rotate(90deg);
        }
        
        .submenu {
            padding-left: 30px;
            overflow: hidden;
            max-height: 0;
            transition: max-height 0.3s ease-out;
        }
        
        .submenu.open {
            max-height: 1000px;
        }
        
        .submenu .menu-item {
            padding-left: 20px;
        }
        
        .content-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        
        .tabs-container {
            height: 40px;
            background-color: #fff;
            border-bottom: 1px solid #dcdfe6;
            display: flex;
            overflow-x: auto;
        }
        
        .tab-item {
            padding: 0 20px;
            display: flex;
            align-items: center;
            border-right: 1px solid #dcdfe6;
            cursor: pointer;
            position: relative;
            min-width: 120px;
            justify-content: space-between;
        }
        
        .tab-item.active {
            color: #409EFF;
            background-color: #ecf5ff;
        }
        
        .tab-item .close-tab {
            margin-left: 8px;
            font-size: 12px;
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }
        
        .tab-item .close-tab:hover {
            background-color: #c0c4cc;
            color: white;
        }
        
        /* 添加右键菜单样式 */
        .context-menu {
            position: fixed;
            background-color: white;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            z-index: 1000;
            display: none;
        }
        
        .context-menu-item {
            padding: 8px 16px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .context-menu-item:hover {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .iframe-container {
            flex: 1;
            position: relative;
        }
        
        .iframe-wrapper {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: none;
        }
        
        .iframe-wrapper.active {
            display: block;
        }
        
        .iframe-page {
            width: 100%;
            height: 100%;
            border: none;
        }
        
        .toggle-button {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 18px;
            margin-right: 15px;
        }
        
        .logout-btn {
            background-color: #f56c6c;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .logout-btn:hover {
            background-color: #e45656;
        }
        
        .hidden {
            display: none;
        }
        
        .loading {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(255, 255, 255, 0.8);
            z-index: 10;
        }
        
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409EFF;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 顶部导航栏 -->
        <div class="header">
            <div class="left-section">
                <button class="toggle-button" id="toggleSidebar">☰</button>
                <div class="logo">后台管理系统</div>
            </div>
            <div class="user-actions">
                <div id="userInfo"></div>
                <button class="logout-btn" id="logoutBtn">退出登录</button>
            </div>
        </div>
        
        <div class="main-container">
            <!-- 左侧菜单栏 -->
            <div class="sidebar" id="sidebar">
                <div class="menu-container" id="menuContainer">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </div>
            </div>
            
            <div class="content-area">
                <!-- 顶部标签栏 -->
                <div class="tabs-container" id="tabsContainer">
                    <!-- 标签将通过JavaScript动态生成 -->
                </div>
                
                <!-- iframe内容区域 -->
                <div class="iframe-container" id="iframeContainer">
                    <!-- iframe将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    
    <script>
        // 当前激活的标签页
        let activeTabId = null;
        // 打开的标签页列表
        let openTabs = [];
        // 菜单数据
        let menuData = [];
        // 展开的菜单项
        let expandedMenus = new Set();
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', async function() {
            // 绑定事件
            bindEvents();
            
            // 获取用户信息
            await loadUserInfo();
            
            // 加载菜单数据
            await loadMenuData();
            
            // 渲染菜单
            renderMenu();
        });
        
        // 绑定事件
        function bindEvents() {
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', function() {
                document.cookie = "access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
                localStorage.removeItem('jwt_token');
                window.location.href = '/login';
            });
            
            // 切换侧边栏
            document.getElementById('toggleSidebar').addEventListener('click', function() {
                const sidebar = document.getElementById('sidebar');
                sidebar.classList.toggle('collapsed');
            });
        }
        
        // 获取用户信息
        async function loadUserInfo() {
            try {
                const response = await fetch('/api/auth/profile', {
                    credentials: 'include'
                });
                const result = await response.json();
                // 根据统一API响应格式获取用户数据
                const user = result.data;
                const username = user.username || user.name || user.user || '未知用户';
                document.getElementById('userInfo').innerHTML = `
                    <span>欢迎您，${username}</span>
                `;
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        }
        
        // 加载菜单数据
        async function loadMenuData() {
            try {
                const response = await fetch('/menu/tree', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    // 确保menuData是一个数组，从result.data中获取菜单数据
                    menuData = Array.isArray(result.data) ? result.data : [];
                } else if (response.status === 401) {
                    // 未授权访问，清除可能存在的token并跳转到登录页
                    document.cookie = "access_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
                    window.location.href = '/login';
                    menuData = [];
                } else {
                    console.error('加载菜单数据失败，HTTP状态码:', response.status);
                    menuData = [];
                }
            } catch (error) {
                console.error('加载菜单数据异常:', error);
                menuData = [];
            }
        }
        
        // 渲染菜单
        function renderMenu() {
            const menuContainer = document.getElementById('menuContainer');
            menuContainer.innerHTML = '';
            
            // 确保menuData是数组
            if (!Array.isArray(menuData)) {
                console.error('菜单数据格式错误，期望数组但得到:', typeof menuData, menuData);
                menuData = [];
            }
            
            function createMenuItem(menu, isSubmenu = false) {
                const menuItem = document.createElement('div');
                menuItem.className = isSubmenu ? 'menu-item submenu' : 'menu-item';
                menuItem.dataset.id = menu.id;
                menuItem.dataset.path = menu.path;
                
                // 判断是否有子菜单
                const hasChildren = menu.children && menu.children.length > 0;
                
                menuItem.innerHTML = `
                    <span>${menu.icon || (hasChildren ? '📁' : '📄')} ${menu.name}</span>
                    ${hasChildren ? '<span class="arrow">▶</span>' : ''}
                `;
                
                menuItem.addEventListener('click', function(e) {
                    e.stopPropagation();
                    
                    if (hasChildren) {
                        // 切换子菜单展开/收起状态
                        toggleSubMenu(menu.id);
                    } else if (menu.path && menu.path !== '#') {
                        // 打开标签页
                        openTab(menu);
                        
                        // 更新激活状态
                        document.querySelectorAll('.menu-item').forEach(item => {
                            item.classList.remove('active');
                        });
                        this.classList.add('active');
                    }
                });
                
                return menuItem;
            }
        
            function renderMenuRecursive(menus, container, level = 0) {
                // 确保menus是数组
                if (!Array.isArray(menus)) {
                    console.error('期望菜单数组但得到:', typeof menus, menus);
                    return;
                }
                
                menus.forEach(menu => {
                    const menuItem = createMenuItem(menu, level > 0);
                    container.appendChild(menuItem);
                    
                    if (menu.children && menu.children.length > 0) {
                        const submenuContainer = document.createElement('div');
                        submenuContainer.className = 'submenu';
                        submenuContainer.id = `submenu-${menu.id}`;
                        
                        // 如果菜单是展开的，添加open类
                        if (expandedMenus.has(menu.id)) {
                            submenuContainer.classList.add('open');
                            menuItem.querySelector('.arrow')?.classList.add('rotated');
                        }
                        
                        renderMenuRecursive(menu.children, submenuContainer, level + 1);
                        container.appendChild(submenuContainer);
                    }
                });
            }
            
            renderMenuRecursive(menuData, menuContainer);
        }
        
        // 切换子菜单展开/收起
        function toggleSubMenu(menuId) {
            const submenu = document.getElementById(`submenu-${menuId}`);
            const menuItem = [...document.querySelectorAll('.menu-item')].find(item => 
                parseInt(item.dataset.id) === menuId);
            
            if (submenu) {
                submenu.classList.toggle('open');
                const arrow = menuItem?.querySelector('.arrow');
                if (arrow) {
                    arrow.classList.toggle('rotated');
                }
                
                // 记录展开状态
                if (submenu.classList.contains('open')) {
                    expandedMenus.add(menuId);
                } else {
                    expandedMenus.delete(menuId);
                }
            }
        }
        
        // 打开标签页
        function openTab(menu) {
            // 检查标签是否已经打开
            const existingTab = openTabs.find(tab => tab.id === menu.id);
            
            if (existingTab) {
                // 切换到已存在的标签
                switchTab(existingTab.id);
            } else {
                // 创建新的标签
                const newTab = {
                    id: menu.id,
                    title: menu.name,
                    path: menu.path
                };
                
                openTabs.push(newTab);
                renderTabs();
                createIframe(newTab);
                switchTab(newTab.id);
            }
        }
        
        // 在新窗口打开页面
        function openInNewWindow(path) {
            window.open(path, '_blank');
        }
        
        // 渲染标签页
        function renderTabs() {
            const tabsContainer = document.getElementById('tabsContainer');
            tabsContainer.innerHTML = '';
            
            openTabs.forEach(tab => {
                const tabElement = document.createElement('div');
                tabElement.className = `tab-item ${tab.id === activeTabId ? 'active' : ''}`;
                tabElement.dataset.id = tab.id;
                
                tabElement.innerHTML = `
                    <span>${tab.title}</span>
                    <span class="close-tab" onclick="closeTab(event, ${tab.id})">✕</span>
                `;
                
                tabElement.addEventListener('click', function(e) {
                    if (!e.target.classList.contains('close-tab')) {
                        switchTab(tab.id);
                    }
                });
                
                // 添加右键菜单事件
                tabElement.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    showContextMenu(e.clientX, e.clientY, tab.path);
                });
                
                tabsContainer.appendChild(tabElement);
            });
        }
        
        // 创建右键菜单
        function showContextMenu(x, y, path) {
            // 移除已存在的菜单
            const existingMenu = document.getElementById('contextMenu');
            if (existingMenu) {
                existingMenu.remove();
            }
            
            // 创建新菜单
            const contextMenu = document.createElement('div');
            contextMenu.className = 'context-menu';
            contextMenu.id = 'contextMenu';
            contextMenu.style.left = x + 'px';
            contextMenu.style.top = y + 'px';
            
            contextMenu.innerHTML = `
                <div class="context-menu-item" onclick="openInNewWindow('${path}'); hideContextMenu();">在新窗口打开</div>
            `;
            
            document.body.appendChild(contextMenu);
            contextMenu.style.display = 'block';
            
            // 创建一个透明遮罩层用于捕获点击事件
            let overlay = document.getElementById('contextMenuOverlay');
            if (!overlay) {
                overlay = document.createElement('div');
                overlay.id = 'contextMenuOverlay';
                overlay.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    z-index: 999;
                    background: transparent;
                `;
                document.body.appendChild(overlay);
            }
            
            // 点击遮罩层时隐藏菜单和遮罩层
            const hideMenu = function(event) {
                event.stopPropagation();
                hideContextMenu();
            };
            
            overlay.addEventListener('click', hideMenu);
        }
        
        // 隐藏右键菜单
        function hideContextMenu() {
            const contextMenu = document.getElementById('contextMenu');
            const overlay = document.getElementById('contextMenuOverlay');
            
            if (contextMenu) {
                contextMenu.remove();
            }
            
            if (overlay) {
                overlay.remove();
            }
        }
        
        // 创建iframe
        function createIframe(tab) {
            const iframeContainer = document.getElementById('iframeContainer');
            
            // 创建iframe容器
            const iframeWrapper = document.createElement('div');
            iframeWrapper.className = 'iframe-wrapper';
            iframeWrapper.id = `iframe-${tab.id}`;
            
            // 创建加载提示
            const loadingElement = document.createElement('div');
            loadingElement.className = 'loading';
            loadingElement.id = `loading-${tab.id}`;
            loadingElement.innerHTML = '<div class="spinner"></div>';
            
            // 创建iframe
            const iframe = document.createElement('iframe');
            iframe.className = 'iframe-page';
            iframe.src = tab.path;
            iframe.frameBorder = '0';
            
            // iframe加载完成后隐藏加载提示
            iframe.onload = function() {
                const loading = document.getElementById(`loading-${tab.id}`);
                if (loading) {
                    loading.style.display = 'none';
                }
            };
            
            iframeWrapper.appendChild(loadingElement);
            iframeWrapper.appendChild(iframe);
            iframeContainer.appendChild(iframeWrapper);
        }
        
        // 切换标签页
        function switchTab(tabId) {
            activeTabId = tabId;
            
            // 更新标签激活状态
            renderTabs();
            
            // 显示对应的iframe
            document.querySelectorAll('.iframe-wrapper').forEach(wrapper => {
                wrapper.classList.remove('active');
            });
            
            const activeIframe = document.getElementById(`iframe-${tabId}`);
            if (activeIframe) {
                activeIframe.classList.add('active');
            }
        }
        
        // 关闭标签页
        function closeTab(event, tabId) {
            event.stopPropagation();
            
            // 阻止关闭最后一个标签页
            if (openTabs.length <= 1) {
                alert('至少保留一个标签页');
                return;
            }
            
            // 找到要关闭的标签索引
            const tabIndex = openTabs.findIndex(tab => tab.id === tabId);
            if (tabIndex === -1) return;
            
            // 移除标签
            openTabs.splice(tabIndex, 1);
            
            // 移除对应的iframe
            const iframeToRemove = document.getElementById(`iframe-${tabId}`);
            if (iframeToRemove) {
                iframeToRemove.remove();
            }
            
            // 如果关闭的是当前激活的标签，则激活下一个或上一个标签
            if (tabId === activeTabId) {
                if (tabIndex < openTabs.length) {
                    switchTab(openTabs[tabIndex].id);
                } else if (openTabs.length > 0) {
                    switchTab(openTabs[openTabs.length - 1].id);
                }
            }
            
            renderTabs();
        }
    </script>
</body>
</html>